/**
 * copyright 2007, hi5 networks 
 *
 * A namespace to avoid clobbering of sandbox and gadget variables.
 */
var Sandbox = function() {

  /**
    * {String} type Application type: profile, canvas, preview
    *
   */
  this.type = null;

 /**
   * {String} gadgetURL URL to the gadget definition file.
   * @private
   */
  this.gadgetUrl = [];

  /**
    * {String} installedApps URLs to already installed applications
    * @private
    */
  this.installedApps = []

  /**
   * {opensocial.Container} Hi5Container maps to Hi5 API
   */
  this.hi5Container = new opensocial.Hi5Container();

  this.defaultstate = null;
// TODO needed?
  var onloadHandlers = [];
  var numHandlers = 0;
};

/**
 * Arbitrary value for setting when the gadget url cookie will expire
 */
Sandbox.COOKIE_EXPIRE_DAYS = 365;



/**
 * Initialize the page by loading previously set values, primarily
 * for convenience.
 */
Sandbox.prototype.init = function (type, state, apps) {
  // Set up the container to be ours
  opensocial.Container.setContainer(this.hi5Container);

  // Try to determine the initial context/state
  if (state) {
      this.defaultstate = state;
  } else {
      if (document.location.hash.length > 1) {
         this.defaultstate = eval('(' + document.location.hash.substring(1) + ')');
      }
  }
  this.state = this.defaultstate;
  this.prepState();

  this.type = type;
  this.installedApps = apps;
}

/**
 * Load the gadget from the specified URL.
 */
Sandbox.prototype.addGadget = function(appUrl, appIndex, state) {
    // Get the gadget url field
    this.gadgetUrl[appIndex] = appUrl;
    //this.gadgetContentDiv = document.getElementById("hi5_gadgetContent"+this.appIndex);

    // allow default state to be overriden
    if (state) {
       this.onLoadState(state, appIndex);
    } else {
    	this.onLoadState(this.defaultstate, appIndex);
    }
    //refreshGadget(appIndex);
}

Sandbox.prototype.addOnLoadHandler = function(func) {
    onloadHandlers[numHandlers++] = func;
}


Sandbox.prototype.prepState = function() {
	// Set viewer from state
	viewer = null;
        if (this.state == null) return;
        if (this.state.container == null) return;
	j = this.state.container.viewer;
	if (j)
		viewer = new opensocial.Hi5Person(j.id,
    		{name : j.name, picture: j.pictureUrl},
			 j.isViewerObject, true);
			 
	// Set owner from initial state
	owner = null;
    j = this.state.container.owner;
    if (j)
		owner = new opensocial.Hi5Person(j.id,
    		{name : j.name, picture: j.pictureUrl},
		 	j.isViewerObject, false);
    
    // Default internal storage to null, fetch on demand
	friends = null;
	activities = null;

    // Initialize the container with the state that has been read
    this.hi5Container.init(viewer, owner, friends, activities);
}

/**
 * This function will get called after successful download of the
 * container state XML.
 */
Sandbox.prototype.onLoadState = function(state, appIndex) {
    if(state == null) {
      alert('Invalid container state');
      return;
    }
    
    this.prepState();
    // Now load the gadget
   this.refreshGadget(appIndex);
  }

/**
 * Make an ajax request to fetch the gadget definition.
 */
Sandbox.prototype.refreshGadget = function(appIndex) {
  // If there is no URL specified, please ask user to enter one
  if (this.gadgetUrl[appIndex].length <= 0) {
    alert('Please enter a gadget location url.');
    return;
  }

  var url = this.gadgetUrl[appIndex];

  // if url starts with http then use built-in proxy
  if (url.substring(0,4) == "http") {
  	url = "http://" + document.location.host + "/friend/proxy/" + escape(url);
  }

  // Fetch the gadget content from the site via proxy
  $(function() {
    $.ajax({type: "GET", url: url, dataType: "xml", timeout: 5000,
      error: function(xhr, textStatus, errorThrown) {
        alert('Cannot fetch gadget info from ' + url + " " + textStatus);
      },
      success: function(gadgetXml) {
          sandbox.onLoadGadget(gadgetXml, appIndex);
      }
    }); // ajax request
  }); // jquery function call
};



/**
 * This function will get called after successful download of the gadget XML.
 */
Sandbox.prototype.onLoadGadget = function(xmlGadget, appIndex) {
    var content = 'No valid html content in gadget definition.'; // will get displayed only on error
    var title = 'Gadget'; // place holder name in case there is no title
    $(xmlGadget).find('ModulePrefs').each(function(){
      title = $(this).attr('title');
    });
    var type = $(xmlGadget).find('Content').attr('type');
    $(xmlGadget).find('Content').each(function(){
      content = $(this).text();
    });

    // Build up the title area text and then the gadget content itself
    //var htmlText = "<div class='section'><h1 class='bg_title box_profile_info_large_heading'>" + title + "</h1><div class='content window_content'><div class='subsection'>"+content+"</div></div><div class='footer'>&nbsp;</div></div><div class='section-separator'></div>";
      var contentHeight = 900;
      if(this.type == 'profile' || this.type == 'preview' || this.type == 'homepage') {
        contentHeight = 400;
      }
      if(type != "html-inline") {
        // pass our state into the iframe, set various pieces of data
        content = "<iframe src='http://0.gmodules.com/ig/ifr?url=http://" + document.location.host + "/friend/proxy/" + this.gadgetUrl[appIndex] + "&amp;parent=http://" + document.location.host + "&amp;lang=en-US&amp;country=US&amp;synd=hi5&amp;mode=" + this.type + "&amp;nocache=2147483647&amp;mid=0&amp;h=280#" + escape(goog.json.serialize(this.state)) + "' id='remote_iframe_" + appIndex + "' name='remote_iframe_" + appIndex + "' width='100%' height='" + contentHeight + "' frameborder='0'></iframe>";
      } else {
        // wrap inline into a 100% wide / contentHeight div
        content = '<div style="width: 100%; display: block; height: ' + contentHeight + 'px">' + content + '</div>';
      }
      var htmlText = "<div class='content window_content'><div class='subsection'>" + content + "</div></div>";
    // JQuery will not evaluate correctly if there is a '.' in the middle of the div id.
    // Hence the '_'
    $("#hi5_gadgetContent" + appIndex).html(htmlText);
    //if(onloadHandlers != null) {
    //    var i;
    //    for(i = 0; i < onloadHandlers.length; i++) {
    //        alert("Running handler: " + onloadHandlers[i]);
    //        onloadHandlers[i].call();
    //    }
    //}
}


